﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsBaiduSearch
{
    public partial class Form1 : Form
    {
        private string text;
        WebClient webClient = new WebClient();
        public Form1()
        {
            InitializeComponent();
        }

        //搜索按钮按下
        async private void buttonSearch_Click(object sender, EventArgs e)
        {
            text = "";
            textBoxResult1.Text = "";
            textBoxResult2.Text = "";
            Random rand = new Random();
            string keyword = textBoxSearch.Text;//获取文本框输入的关键字
            string url = "https://www.baidu.com/s?wd=" + keyword + "&rnd=" + rand.Next();

            //Crawl(url);
            Form1 f1 = new Form1();
            Form1 f2 = new Form1();
            /*
            //多线程
            Form1 f1 = new Form1();
            Form1 f2 = new Form1();
            Thread thread1 = new Thread(() => f1.Crawl(url));
            Thread thread2 = new Thread(() => f2.Crawl(url));
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();
            */
            /*
            //同步
            Task[] tasks = { Task.Run(() => f1.Crawl(url)), Task.Run(() => f2.Crawl(url))};
            Task.WaitAll(tasks);
            */
            //异步
            textBoxResult1.Text = await AccessTheWebAsync(url);
            textBoxResult2.Text = await AccessTheWebAsync(url);
            /*
            if (f1.text!=null&&f1.text.Length > 200)
            {
                textBoxResult1.Text = f1.text.Substring(0, 200);
              
            }
            else if(f1.text==null)
            {
                textBoxResult1.Text = "";
            }
            else
            {
                textBoxResult1.Text = f1.text.Substring(0);
            }
            if (f2.text.Length > 200)
            {
                textBoxResult2.Text = f2.text.Substring(0, 200);

            }
            else if (f2.text == null)
            {
                textBoxResult2.Text = "";
            }
            else
            {
                textBoxResult2.Text = f2.text.Substring(0);
            }
            */

        }
            

        //爬取方法
        private void Crawl(string url)
        {
            try
            {

                webClient.Encoding = Encoding.UTF8;
                webClient.Credentials = CredentialCache.DefaultCredentials;
                webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";

                
               // webClient.Headers["Cookie"] = "PSTM=1610001668; BIDUPSID=6DE73C37B37D8FC77AEF702097C061E1; __yjs_duid=1_9ea0f63f59015d22a3689e459951feeb1618378240600; BAIDU_WISE_UID=wapp_1641634408445_302; BDUSS=hEOVdWanZDRUZOVERkTGYtVEJFYjZRT1A0ejQzelF1WXNpSVowcE1aUjhSRnhpRVFBQUFBJCQAAAAAAQAAAAEAAAASNkYkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHy3NGJ8tzRiOW; BDUSS_BFESS=hEOVdWanZDRUZOVERkTGYtVEJFYjZRT1A0ejQzelF1WXNpSVowcE1aUjhSRnhpRVFBQUFBJCQAAAAAAQAAAAEAAAASNkYkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHy3NGJ8tzRiOW; BAIDUID=D8907B203CD66C52199B0EA616087A0D:FG=1; BD_UPN=12314753; BA_HECTOR=25250l8104aka48g3b1h624m10q; BD_HOME=1; H_PS_PSSID=36181_36309_31254_35910_36165_34584_36122_36341_36073_36125_36296_36235_26350_36315_36061; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; BD_CK_SAM=1; PSINO=2; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; channel=baidusearch; H_PS_645EC=1e23kIpwvv%2BYCx94%2FSV5GYSYHEEV5inj%2BRzuskILaJeyrITzCm3fHZ5z49YAsH2gS7uU; baikeVisitId=6a00c661-6650-4d9d-9149-0f39152ae1ad; B64_BOT=1";
                string html = webClient.DownloadString(url);//下载
                MatchCollection TitleMatchs = Regex.Matches(html, @"(<div class=""c-font-normal c-color-text"" aria-label=""([\s\S]*?)>|<span class=""content-right_8Zs40""> ([\s\S]*?)</span>)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (Match NextMatch in TitleMatchs)
                {
                    text += NextMatch.Groups[1].Value;
                }
            }
            catch(Exception ex)
            {
                label2.Text = ex.Message;
            } 
        }

        //异步方法
        async Task<string> AccessTheWebAsync(string url)
        {
            label2.Text = "";
            try
            {

                webClient.Encoding = Encoding.UTF8;
                webClient.Credentials = CredentialCache.DefaultCredentials;
                webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";


                // webClient.Headers["Cookie"] = "PSTM=1610001668; BIDUPSID=6DE73C37B37D8FC77AEF702097C061E1; __yjs_duid=1_9ea0f63f59015d22a3689e459951feeb1618378240600; BAIDU_WISE_UID=wapp_1641634408445_302; BDUSS=hEOVdWanZDRUZOVERkTGYtVEJFYjZRT1A0ejQzelF1WXNpSVowcE1aUjhSRnhpRVFBQUFBJCQAAAAAAQAAAAEAAAASNkYkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHy3NGJ8tzRiOW; BDUSS_BFESS=hEOVdWanZDRUZOVERkTGYtVEJFYjZRT1A0ejQzelF1WXNpSVowcE1aUjhSRnhpRVFBQUFBJCQAAAAAAQAAAAEAAAASNkYkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHy3NGJ8tzRiOW; BAIDUID=D8907B203CD66C52199B0EA616087A0D:FG=1; BD_UPN=12314753; BA_HECTOR=25250l8104aka48g3b1h624m10q; BD_HOME=1; H_PS_PSSID=36181_36309_31254_35910_36165_34584_36122_36341_36073_36125_36296_36235_26350_36315_36061; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; BD_CK_SAM=1; PSINO=2; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; channel=baidusearch; H_PS_645EC=1e23kIpwvv%2BYCx94%2FSV5GYSYHEEV5inj%2BRzuskILaJeyrITzCm3fHZ5z49YAsH2gS7uU; baikeVisitId=6a00c661-6650-4d9d-9149-0f39152ae1ad; B64_BOT=1";
                //string html = webClient.DownloadString(url);//下载
                Task<string> getStringTask = webClient.DownloadStringTaskAsync(url);
                label2.Text += "Working......\r\n";
                string html = await getStringTask;
                MatchCollection TitleMatchs = Regex.Matches(html, @"(<div class=""c-font-normal c-color-text"" aria-label=""([\s\S]*?)>|<span class=""content-right_8Zs40""> ([\s\S]*?)</span>|<div class=""text_2NOr6""> ([\s\S]*?)</span>)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (Match NextMatch in TitleMatchs)
                {
                    text += NextMatch.Groups[2].Value;
                }
                MatchCollection TitleMatchs2 = Regex.Matches(html, @"<span class=""content-right_8Zs40""> ([\s\S]*?)</span>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (Match NextMatch in TitleMatchs2)
                {
                    text += NextMatch.Groups[2].Value;
                }
                MatchCollection TitleMatchs3 = Regex.Matches(html, @"<div class=""content-right_8Zs40""> ([\s\S]*?)</span>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (Match NextMatch in TitleMatchs3)
                {
                    text += NextMatch.Groups[3].Value;
                }
                return text;
            }
            catch (Exception ex)
            {
                label2.Text = ex.Message;
                return "";
            }
        }

    }
}
